package com.jwttest.jwt.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jwttest.jwt.model.User;
import com.jwttest.jwt.utils.JwtTokenUtils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * author: MaHX
 * date: 2019/10/28/20:26
 * description:  jwt过滤器 做登录信息校验，以及对成功和失败进行处理
 * 拦截器里面的实现需要一些组件来实现，所以就有了AuthenticationManager、accessDecisionManager等组件来支撑
 *
 **/
public class JwtLoginFilter extends AbstractAuthenticationProcessingFilter {
    public JwtLoginFilter(String defaultFilterProcessesUrl, AuthenticationManager authenticationManager) {
        super(new AntPathRequestMatcher(defaultFilterProcessesUrl));
        setAuthenticationManager(authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException {
        //从输入流中获取登录信息
        User user = new ObjectMapper().readValue(req.getInputStream(),User.class);
        return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword()));

    }

    /**
     * 登录成功
     * @param request
     * @param response
     * @param chain
     * @param authResult
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        //获取该角色的权限
        Collection<? extends GrantedAuthority> authorities = authResult.getAuthorities();
        StringBuffer sb = new StringBuffer();
        for (GrantedAuthority authority : authorities){
            sb.append(authority.getAuthority()).append(",");
        }
        String jwt = Jwts.builder()
                .claim("authorities",sb)
                .setSubject(authResult.getName())
                .setExpiration(new Date(System.currentTimeMillis()+60*60*1000)) //60分钟
                .signWith(SignatureAlgorithm.HS512,"javaboy@123")
                .compact();
//        String jwt = JwtTokenUtils.createToken(authResult.getName(),false);
        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);
        map.put("msg","登录成功");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(new ObjectMapper().writeValueAsString(map));
        out.flush();
        out.close();
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        Map<String,String> map = new HashMap<>();
        String errorMsg = null;
        if (e instanceof BadCredentialsException ||
                e instanceof UsernameNotFoundException) {
            errorMsg = "账户名或者密码输入错误!";
        } else if (e instanceof LockedException) {
            errorMsg = "账户被锁定，请联系管理员!";
        } else if (e instanceof CredentialsExpiredException) {
            errorMsg = "密码过期，请联系管理员!";
        } else if (e instanceof AccountExpiredException) {
            errorMsg = "账户过期，请联系管理员!";
        } else if (e instanceof DisabledException) {
            errorMsg = "账户被禁用，请联系管理员!";
        } else {
            errorMsg = "登录失败!";
        }
        map.put("msg",errorMsg);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(new ObjectMapper().writeValueAsString(map));
        out.flush();
        out.close();
    }
}
